package com.luo;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.pipeline.FilePipeline;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class GetQiDian implements PageProcessor {

    private Site sit = Site.me()
            .setCharset("UTF-8") //设置爬取的字符集
            .setSleepTime(1000) //设置爬取时的休眠时间
            .setCycleRetryTimes(4)  //设置爬虫重复次数
            .setTimeOut(10000); //设置爬取网络超时时间

    @Override
    public Site getSite() {
        return sit;
    }

    //获取爬取时的爬取参数

    //校验内容URL
    private String regexC= "https://read.qidian.com/chapter/.{23}/.{23}";
    //校验章节列表URL
    private String regexT= "https://book.qidian.com/info/\\d{10}#Catalog";
    //校验书籍列表URL
    private String regexB= "https://www.qidian.com/.*";

    //解析第一章中小说名URL
    private String xpathFB = "[@id=j_readMainWrap]/div[1]/div[1]/div[1]/div[1]/h1/text()";
    //解析非第一章小说名URL
    private String xpathB = "[@id=j_readMainWrap]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/a/text()";
    //解析第一章中标题URL
    private String xpathFT = "[@id=j_readMainWrap]/div[1]/div[2]/div[1]/div[1]/h3/span/text()";
    //解析第一章中内容URL
    private String xpathFC = "[@id=j_readMainWrap]/div[1]/div[2]/div[1]/div[2]/p/text()";
    //解析非第一章中标题URL
    private String xpathT = "[@id=j_readMainWrap]/div[1]/div[1]/div[1]/div[1]/h3/span/text()";
    //解析非第一章中内容URL
    private String xpathC = "[@id=j_readMainWrap]/div[1]/div[1]/div[1]/div[2]/p/text()";

    //解析章节目录URL
    private String xpathTL = "[@id=j-catalogWrap]/div[2]/div[1]/ul/li/a/@href";
    //解析小说目录URL
    private String xpathCatalog = "[@id=new-book-list]/div/ul/li/div[1]/a/@href";


    //设置爬取数据的逻辑
    @Override
    public void process(Page page) {
        //通过page先获取URL，然后再获取页面对象
        Selectable table = page.getUrl();
        System.out.println(System.currentTimeMillis());
        //获取Html页面信息
        Html html;

        if (table.regex(regexC).match()){ //这里获取的就是每一章节的内容
            html = page.getHtml();
            //抓取有用的信息
            //设定一个字段串存储章节标题
            String title;
            //获取书名
            String book = html.xpath(xpathFB).toString();
            //获取章节正文内容
            List<String> content;
            //判断是否时第一章
             if(book != null) {
                 title = html.xpath(xpathFT).toString();
                 content = html.xpath(xpathFC).all();
                 page.putField("title",title);
                 page.putField("bookName",book);
                 page.putField("content",content);
             } else{
                 //获取书名
                 book = html.xpath(xpathB).toString();
                 //获取章节名
                 title = html.xpath(xpathT).toString();
                 //获取章节内容
                 content = html.xpath(xpathC).all();
                 page.putField("title",title);
                 page.putField("bookName",book);
                 page.putField("content",content);
             }
             //把文章写入文件
            //toFile(book,title,content);


        }else if(table.regex(regexT).match()){ //书的章节目录
            html = page.getHtml();
            //获取章节路径列表
            List<String> list = html.xpath(xpathTL).all();
            page.addTargetRequests(list);
        }else if(table.regex(regexB).match()){
            html = page.getHtml();
            //获取小说路径列表
            List<String> list = html.xpath(xpathCatalog).all();
            List<String> listH = new ArrayList<String>();
            for (String s : list) {
                System.out.println(s);
                listH.add(s+"#Catalog");
            }
            page.addTargetRequests(listH);
        }

    }
    private void toFile(String bookname,String titleName,List<String> context){
        File f = new File("F:/book/"+bookname);
        if(!f.exists()){
            f.mkdirs();
        }
        File f1 = new File("F:/book/"+bookname+"/"+titleName+".txt");
        FileOutputStream fos;
        PrintWriter pw = null;
        try {
            //f1.createNewFile();
            fos = new FileOutputStream(f1);
            pw = new PrintWriter(fos,true);
            for (String s : context) {
                pw.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(pw != null)
                pw.close();
        }

    }

    public static void main(String[] args) {
        String t = "https://www.qidian.com/xuanhuan";
        String t0 = "https://book.qidian.com/info/1019764137#Catalog";
        String t1= "https://read.qidian.com/chapter/SaT8jsiJD54smgY_yC2imA2/oQbX6YtwB_NOBDFlr9quQA2";
        String t2 = "https://read.qidian.com/chapter/C9w9mERKYvLmkXioLmMPXw2/yAAyuUeLAgBMs5iq0oQwLQ2";
        Spider.create(new GetQiDian())
                .thread(10)
                .addUrl(t)
                .addPipeline(new MyPipeline())
                .addPipeline(new MyFilePipeline())
                .run();

    }

}
